<template>
  <div class="img-upload" v-loading="loading">
    <el-upload
      class="avatar-uploader"
      action=""
      :http-request="handleRequest"
      :show-file-list="false"
    >
      <!-- :before-upload="beforeAvatarUpload" -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
  <Button :flag="flag">
    <template #next>
      <el-button type="primary" @click="submit">提交登记›</el-button>
    </template>
  </Button>
</template>

<script lang="ts" setup>
import { getCurrentInstance, ref, onMounted } from "vue";
import Button from "./button.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "@/stores/counter";
import router from "@/router";

const { userInfos } = useStore();
const flag = JSON.parse(window.sessionStorage.getItem("flag") || "true");
//渲染页面的url
const imageUrl = ref("");
//用于存储数据库的url
const saveUrl = ref("");
const loading = ref(false);
const { proxy }: any = getCurrentInstance();

// 获取失联人信息
const loserSinger = ref(
  JSON.parse(window.sessionStorage.getItem("loserForm") || "{}")
);
// 获取联系人信息
const linkSinger = JSON.parse(
  window.sessionStorage.getItem("linkForm") || "{}"
);

//获取本地图片
const handleRequest = (e: any) => {
  const fd = new FileReader();
  fd.readAsDataURL(e.file);
  imageUrl.value = URL.createObjectURL(e.file);
  saveUrl.value = "https://img2.baidu.com/it/" + e.file.name.slice(0, -5);
};

const submit = () => {
  const loserInfo = { ...loserSinger.value, l_photos: saveUrl.value };
  
  if (!imageUrl.value) return ElMessage.error("请上传失联人照片");
  ElMessageBox.confirm("确保信息无误", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "success",
    draggable: true,
  }).then(() => {
    // 调用user与loser的关联接口
    proxy.$http
      .post("/user/addLoser?id=" + userInfos.id, loserInfo)
      .then((res: any) => {
        // 调用loser与linkmans的关联接口
        proxy.$http
          .post("/loser/addmans?id=" + res.data.id, linkSinger)
          .then((res: any) => {
            ElMessage({
              type: "success",
              message: res,
            });
            router.push("/userhome");
            window.sessionStorage.removeItem("flag");
            window.sessionStorage.removeItem("linkForm");
            window.sessionStorage.removeItem("loserForm");
          });
      });
  });
};
</script>

<style scoped lang="less">
.img-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80px 0;
  .avatar-uploader {
    width: 250px;
    height: 250px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dotted gray;

    .avatar {
      width: 240px;
      height: 240px;
    }
  }
}
</style>
